import type { Directive } from 'vue'

const bgLazy: Directive = {
  mounted(el: any, binding, vnode, prevVnode) {
    const imgUrl = binding.value
    console.log(imgUrl)
    if (el.getBoundingClientRect().bottom - el.clientHeight <= window.innerHeight) {
      el.style.backgroundImage = `url(${imgUrl})`
      return
    }

    const handleScroll = () => {
      if (el.getBoundingClientRect().bottom - el.clientHeight <= window.innerHeight) {
        el.style.backgroundImage = imgUrl
        window.removeEventListener('scroll', handleScroll)
      }
    }

    window.addEventListener('scroll', handleScroll)
  }
}

export default bgLazy
